<template>
  <div class="container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input
          v-model="searchKeyword"
          placeholder="请输入问题标题"
          prefix-icon="Search"
          style="width: 300px; margin-right: 16px"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button
          type="danger"
          @click="handleBatchDelete"
          :disabled="selectedIds.length === 0"
      >
        批量删除（{{ selectedIds.length }}）
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
        :data="tableData"
        stripe
        border
        style="width: 100%; margin-top: 20px"
        @selection-change="handleSelectionChange"
        :default-sort="{ prop: 'id', order: 'ascending' }"
    >
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column prop="id" label="ID" sortable width="80" align="center" />
      <el-table-column prop="title" label="问题标题" show-overflow-tooltip />
      <el-table-column prop="content" label="提问内容" show-overflow-tooltip />
      <el-table-column prop="userName" label="提问人" width="120" />
      <el-table-column prop="time" label="提问时间" sortable width="180" />
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="scope">

          <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row.id)"
          >删除问题</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 回复对话框 -->
    <el-dialog
        v-model="replyDialogVisible"
        title="回复问题"
        width="50%"
        :before-close="handleClose"
    >
      <el-form :model="replyForm" label-width="80px">
        <el-form-item label="问题标题">
          <el-input v-model="replyForm.title" disabled />
        </el-form-item>

        <el-form-item label="回复内容">
          <el-input
              v-model="replyForm.reply"
              type="textarea"
              :rows="4"
              placeholder="请输入回复内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="replyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReply">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[2, 5, 10, 20]"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'
import { ElMessageBox, ElMessage } from 'element-plus'

const sortField = ref('id') // 默认排序字段
const sortOrder = ref('asc')

const replyForm = ref({
  id: null,
  title: '',
  reply: ''
})

// 表格数据
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const background = ref(true)
const total = ref(0)
const searchKeyword = ref('')


// 获取数据方法
const fetchData = async () => {
  try {
    const response = await axios.get('/api/questions/all', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    })

    if (response.data.code === 1) {
      tableData.value = response.data.data.rows
      total.value = response.data.data.total
    } else {
      ElMessageBox.alert(response.data.msg, '错误提示')
    }
  } catch (error) {
    ElMessageBox.alert('系统繁忙，请稍后再试', '错误提示')
    console.error(error)
  }
}


// 单个删除（对接后端接口）
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定删除此记录？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })

    // 调用后端删除接口
    const response = await axios.delete(`/api/questions/delete/${id}`)

    if (response.data.code === 1) {
      // 删除成功，更新前端数据
      const index = tableData.value.findIndex(item => item.id === id)
      if (index > -1) {
        tableData.value.splice(index, 1)
        total.value--
      }
      ElMessageBox.alert('删除成功', '提示')
    } else {
      ElMessageBox.alert(response.data.msg, '错误提示')
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessageBox.alert('系统繁忙，请稍后再试', '错误提示')
  }
}


// 生命周期：组件加载时获取数据
onMounted(() => {
  fetchData()
})

// 搜索功能
// const handleSearch = () => {
//   currentPage.value = 1
//   fetchData()
// }

// 分页变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 选择状态管理
const selectedIds = ref([])
const handleSelectionChange = (val) => {
  selectedIds.value = val.map(item => item.id)
}


const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm('确定删除选中所有记录？', '批量删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    console.log('即将发送的IDs:', selectedIds.value)
    const response = await axios.post('/api/questions/batchDelete', selectedIds.value, {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (response.data.code === 1) {
      // 更新前端数据
      selectedIds.value.forEach(id => {
        const index = tableData.value.findIndex(item => item.id === id)
        if (index > -1) {
          tableData.value.splice(index, 1)
        }
      })
      total.value -= selectedIds.value.length
      ElMessageBox.alert(`成功删除 ${response.data.data} 条记录`, '提示')
      selectedIds.value = []
    } else {
      ElMessageBox.alert(response.data.msg, '错误提示')
    }
  } catch (error) {
    console.error('批量删除失败:', error)
    ElMessageBox.alert('系统繁忙，请稍后再试', '错误提示')
  }
}

const handleSearch = async () => {
  try {
    const response = await axios.get('/api/questions/selectByTitle', {
      params: {
        title: searchKeyword.value,
        pageNum: currentPage.value,
        pageSize: pageSize.value
      }
    })

    if (response.data.code === 1) {
      tableData.value = response.data.data.list
      total.value = response.data.data.total
    } else {
      ElMessageBox.alert(response.data.msg, '错误提示')
    }
  } catch (error) {
    ElMessageBox.alert('系统繁忙，请稍后再试', '错误提示')
    console.error(error)
  }
}

// 回复相关

const replyDialogVisible = ref(false)

const handleReply = (row) => {
  replyForm.value = {
    id: row.id,
    title: row.title,
    content: row.content,
    // replyContent: ''
  }
  replyDialogVisible.value = true
}

const handleClose = (done) => {
  ElMessageBox.confirm('确认关闭？')
      .then(() => {
        done()
      })
      .catch(() => {
        // 取消关闭
      })
}
const submitReply = async () => {
  try {
    const response = await axios.post('/api/feedback/add', {
      content: replyForm.value.reply,
      consultantId: 2, // 暂时固定为2，后期从登录用户获取
      quesId: replyForm.value.id,
      del: 1,
      time: new Date().toISOString().slice(0, 19).replace('T', ' ')
    })

    if (response.data.code === 1) {
      replyDialogVisible.value = false
      ElMessageBox.alert('回复成功', '提示')
      fetchData() // 刷新数据
    } else {
      ElMessageBox.alert(response.data.msg || '回复失败', '错误提示')
    }
  } catch (error) {
    console.error('回复失败:', error)
    ElMessageBox.alert('回复失败，请检查网络连接', '错误提示')
  }
}

</script>

<style scoped>
.container {
  padding: 20px;
  background-color: #fff;
}

.search-area {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  justify-content: flex-start;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  text-align: right;
}

.el-table {
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.el-table th {
  background-color: #f5f7fa;
}

.el-button--danger {
  background-color: #F56C6C;
  border-color: #F56C6C;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
